package hy.controller;

import hy.entity.Account;
import hy.entity.User;
import hy.entity.UserVO;
import hy.feign.AccountFeign;
import hy.feign.OrderFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/account")
public class AccountCtrl {
    @Autowired
    private OrderFeign orderFeign;
    @Autowired
    private AccountFeign accountFeign;

    @PostMapping("/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("type") String type, HttpSession session){
        Account account = accountFeign.login(username,password,type);
        System.out.println("account==============="+account);
        String target = null;
        if(account == null){
            target = "redirect:/login.html";
        }else{
            switch (type){
                case "user":
                    session.setAttribute("user",account);
                    target = "index";
                    break;
                case "admin":
                    session.setAttribute("admin",account);
                    target = "main";
                    break;
            }
        }
        return target;
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/login.html";
    }


    @GetMapping("/findAll")
    @ResponseBody
    public UserVO findAll(@RequestParam("page") int page, @RequestParam("limit") int limit){
        return accountFeign.findAll(page, limit);
    }

    @PostMapping("/register")
    public String save(User user){
        accountFeign.save(user);
        return "redirect:/showUser_manage";
    }

    @GetMapping("/deleteById/{id}")
    public String deleteById(@PathVariable("id") long id){
        orderFeign.deleteByUid(id);
        accountFeign.deleteById(id);
        return "redirect:/showUser_manage";
    }
}

